package com.example.draw.algorithm;

import com.example.exception.BusinessException;
import com.example.pojo.LotteryPrize;
import java.util.List;
import java.util.Random;
import org.springframework.stereotype.Component;

/**
 * 权重抽奖算法
 * <p>
 * 该算法根据奖品的权重进行抽奖，权重总和必须大于0。<p>
 * 如果抽中库存不足的奖品，则返回默认奖品（谢谢参与）。
 */
@Component
public class WeightLotteryAlgorithm implements LotteryAlgorithm {

	@Override
	public LotteryPrize draw(List<LotteryPrize> prizes) {
		// 计算总权重
		int totalWeight = prizes.stream()
		                        .mapToInt(p -> p.getWeight() != null ? p.getWeight() : 0)
		                        .sum();

		if (totalWeight <= 0) {
			throw new BusinessException("奖品权重配置错误");
		}

		// 生成随机数
		int random = new Random().nextInt(totalWeight) + 1;
		int currentWeight = 0;

		for (LotteryPrize prize : prizes) {
			currentWeight += prize.getWeight() != null ? prize.getWeight() : 0;
			if (random <= currentWeight) {
				if (prize.getRemainingStock() > 0) {
					return prize;
				}
				break;
			}
		}

		return getDefaultPrize(prizes);
	}
	private LotteryPrize getDefaultPrize(List<LotteryPrize> prizes) {
		return prizes.stream()
		             .filter(p -> "谢谢参与".equals(p.getName()))
		             .findFirst()
		             .orElseThrow(() -> new BusinessException("未配置默认奖品"));
	}

	@Override
	public String getAlgorithmType() {
		return "weight";
	}

	// ... getDefaultPrize方法同上
}
